<template>
  <div id="mapView" class="map-view">
    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox v-model="layerVisibility.sign" @change="toggleLayerVisibility('sign')"
                >标志牌</el-checkbox
              >
              <el-checkbox
                v-model="layerVisibility.highway"
                @change="toggleLayerVisibility('highway')"
                >高速公路</el-checkbox
              >
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="图层操作控制" name="operations">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-button type="primary" @click="startAddSign" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增标志牌
              </el-button>
              <el-button type="warning" @click="showReportedSigns" :disabled="isDrawing">
                <el-icon><Warning /></el-icon> 查看已上报错误标志牌
              </el-button>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 标志牌属性表单对话框 -->
    <el-dialog
      v-model="signFormVisible"
      :title="formMode === 'add' ? '新增标志牌' : '编辑标志牌'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :key="refreshSignKey"
    >
      <el-form :model="signForm" label-width="120px" :rules="signFormRules" ref="signFormRef">
        <el-form-item label="标志牌类型" prop="SignType">
          <el-select v-model="signForm.SignType" placeholder="请选择标志牌类型" style="width: 100%">
            <el-option label="限速" value="限速"></el-option>
            <el-option label="警告" value="警告"></el-option>
            <el-option label="指示" value="指示"></el-option>
            <el-option label="禁止" value="禁止"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标志牌内容" prop="Content">
          <el-input v-model="signForm.Content" placeholder="请输入标志牌内容"></el-input>
        </el-form-item>
        <el-form-item label="安装日期" prop="InstallationDate">
          <el-date-picker
            v-model="signForm.InstallationDate"
            type="date"
            placeholder="请选择安装日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="标牌尺寸" prop="BoardSize">
          <el-input v-model="signForm.BoardSize" placeholder="请输入标牌尺寸"></el-input>
        </el-form-item>
        <el-form-item label="材料" prop="Material">
          <el-select v-model="signForm.Material" placeholder="请选择材料" style="width: 100%">
            <el-option label="铝合金" value="铝合金"></el-option>
            <el-option label="不锈钢" value="不锈钢"></el-option>
            <el-option label="复合材料" value="复合材料"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="Status">
          <el-select v-model="signForm.Status" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="损坏" value="损坏"></el-option>
            <el-option label="待维修" value="待维修"></el-option>
            <el-option label="已报废" value="已报废"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最近检查日期" prop="LastInspectionDate">
          <el-date-picker
            v-model="signForm.LastInspectionDate"
            type="date"
            placeholder="请选择最近检查日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="所属道路段" prop="RoadSegmentID">
          <el-select
            v-model="signForm.RoadSegmentID"
            placeholder="请选择所属道路段"
            style="width: 100%"
          >
            <el-option
              v-for="road in roadList"
              :key="road.attributes.FID"
              :label="road.attributes.RoadName"
              :value="road.attributes.FID.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预期寿命(年)" prop="ExpectedLifespan">
          <el-input-number
            v-model="signForm.ExpectedLifespan"
            :min="1"
            :max="30"
            placeholder="请输入预期寿命"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="受损程度(%)" prop="DamagePercent">
          <el-slider
            v-model="signForm.DamagePercent"
            :min="0"
            :max="100"
            :step="5"
            show-input
            :show-stops="true"
            :marks="{ 0: '0%', 25: '25%', 50: '50%', 75: '75%', 100: '100%' }"
          ></el-slider>
        </el-form-item>
        <el-form-item label="标牌照片" prop="PhotoBase64">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handlePhotoChange"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述/维修描述" prop="Description">
          <el-input
            v-model="signForm.Description"
            type="textarea"
            placeholder="请输入描述"
            :rows="3"
          ></el-input>
        </el-form-item>
        <!-- 仅在编辑模式下显示维护信息 -->
        <template v-if="formMode === 'edit'">
          <el-form-item label="维护日期" prop="MaintenanceDate">
            <el-date-picker
              v-model="signForm.MaintenanceDate"
              type="date"
              placeholder="请选择维护日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="维护类型" prop="MaintenanceType">
            <el-select
              v-model="signForm.MaintenanceType"
              placeholder="请选择维护类型"
              style="width: 100%"
            >
              <el-option label="清洗" value="清洗"></el-option>
              <el-option label="更换" value="更换"></el-option>
              <el-option label="修复" value="修复"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelSignForm">取消</el-button>
          <el-button type="primary" @click="submitSignForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 标志牌属性查看对话框 -->
    <el-dialog v-model="signInfoVisible" title="标志牌信息" width="500px" :key="refreshSignKey">
      <div v-if="selectedSign">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="标志牌类型">{{
            selectedSign.attributes.SignType
          }}</el-descriptions-item>
          <el-descriptions-item label="标志牌内容">{{
            selectedSign.attributes.Content
          }}</el-descriptions-item>
          <el-descriptions-item label="安装日期">{{
            selectedSign.attributes.InstallationDate
          }}</el-descriptions-item>
          <el-descriptions-item label="标牌尺寸">{{
            selectedSign.attributes.BoardSize
          }}</el-descriptions-item>
          <el-descriptions-item label="材料">{{
            selectedSign.attributes.Material
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{
            selectedSign.attributes.Status
          }}</el-descriptions-item>
          <el-descriptions-item label="最近检查日期">{{
            selectedSign.attributes.LastInspectionDate
          }}</el-descriptions-item>
          <el-descriptions-item label="所属道路段">{{
            getRoadNameById(selectedSign.attributes.RoadSegmentID)
          }}</el-descriptions-item>
          <el-descriptions-item label="预期寿命"
            >{{ selectedSign.attributes.ExpectedLifespan }} 年</el-descriptions-item
          >
          <el-descriptions-item label="受损程度">
            <el-progress
              :percentage="Number(selectedSign.attributes.DamagePercent || 0)"
              :status="getDamageStatus(selectedSign.attributes.DamagePercent)"
            ></el-progress>
          </el-descriptions-item>
          <el-descriptions-item label="维护日期" v-if="selectedSign.attributes.MaintenanceDate">{{
            selectedSign.attributes.MaintenanceDate
          }}</el-descriptions-item>
          <el-descriptions-item label="维护类型" v-if="selectedSign.attributes.MaintenanceType">{{
            selectedSign.attributes.MaintenanceType
          }}</el-descriptions-item>
          <el-descriptions-item label="描述/维护描述">{{
            selectedSign.attributes.Description
          }}</el-descriptions-item>
          <el-descriptions-item label="标牌照片" v-if="selectedSign.attributes.PhotoBase64">
            <img
              :src="'data:image/jpeg;base64,' + selectedSign.attributes.PhotoBase64"
              style="max-width: 100%; max-height: 200px"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="signInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editSign">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteSign">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
      <p>确定要删除该标志牌吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteSign">确定删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 已上报错误标志牌列表对话框 -->
    <el-dialog v-model="reportedSignsVisible" title="已上报错误标志牌" width="800px">
      <div v-if="reportedSigns.length > 0">
        <el-table :data="reportedSigns" style="width: 100%" @row-click="handleReportedSignClick">
          <el-table-column prop="signType" label="标志牌类型" width="120"></el-table-column>
          <el-table-column prop="content" label="标志牌内容"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag type="danger" v-if="scope.row.status === '待维修'">{{
                scope.row.status
              }}</el-tag>
              <el-tag type="warning" v-else-if="scope.row.status === '损坏'">{{
                scope.row.status
              }}</el-tag>
              <el-tag v-else>{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.stop="viewReportedSignDetail(scope.$index)"
                >查看详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-empty description="未找到已上报错误的标志牌"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportedSignsVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus, Warning } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'

type SignFormType = {
  SignType: string
  Content: string
  InstallationDate: string
  BoardSize: string
  Material: string
  Status: string
  LastInspectionDate: string
  RoadSegmentID: string
  PhotoBase64: string
  ExpectedLifespan: string
  MaintenanceDate: string
  MaintenanceType: string
  Description: string
  DamagePercent: string
}

let view: MapView | null = null
let signLayer: FeatureLayer | null = null
let highwayLineLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let tempGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  sign: true,
  highway: true,
}) as any

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'operations'])
// 添加一个刷新标记
const refreshSignKey = ref(0)

// 表单相关
const signFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const signFormVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const isDrawing = ref(false)
const signInfoVisible = ref(false)
const deleteConfirmVisible = ref(false)
const reportedSignsVisible = ref(false)
let selectedSign: Graphic | null = null
let reportedSignsGraphics: Graphic[] = []
const reportedSigns = ref<any[]>([])

// 图片上传相关
const imageUrl = ref('')

// 将响应式变量改回普通变量
let roadList: Graphic[] = []

// 标志牌表单数据
const signForm = reactive<SignFormType>({
  SignType: '',
  Content: '',
  InstallationDate: '',
  BoardSize: '',
  Material: '',
  Status: '正常',
  LastInspectionDate: '',
  RoadSegmentID: '',
  PhotoBase64: '',
  ExpectedLifespan: '10',
  MaintenanceDate: '',
  MaintenanceType: '',
  Description: '',
  DamagePercent: '0',
})
// 标志牌表单验证规则
const signFormRules = {
  SignType: [{ required: true, message: '请选择标志牌类型', trigger: 'change' }],
  Content: [{ required: true, message: '请输入标志牌内容', trigger: 'blur' }],
  InstallationDate: [{ required: true, message: '请选择安装日期', trigger: 'change' }],
  BoardSize: [{ required: true, message: '请输入标牌尺寸', trigger: 'blur' }],
  Material: [{ required: true, message: '请选择材料', trigger: 'change' }],
  Status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  LastInspectionDate: [{ required: true, message: '请选择最近检查日期', trigger: 'change' }],
  RoadSegmentID: [{ required: true, message: '请选择所属道路段', trigger: 'change' }],
  ExpectedLifespan: [{ required: true, message: '请输入预期寿命', trigger: 'change' }],
  Description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
}
// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  if (layerType === 'sign' && signLayer) {
    signLayer.visible = Boolean(layerVisibility.value.sign)
  } else if (layerType === 'highway' && highwayLineLayer) {
    highwayLineLayer.visible = Boolean(layerVisibility.value.highway)
  }
}

// 开始添加标志牌
const startAddSign = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击添加标志牌位置')

  // 开始绘制点
  sketchViewModel.create('point')
}

// 处理照片上传
const handlePhotoChange = (file: any) => {
  // 压缩图片
  compressImage(file.raw)
}

// 图片压缩函数
const compressImage = (file: File) => {
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = (e) => {
    const img = new Image()
    img.src = e.target?.result as string
    img.onload = () => {
      // 创建canvas
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')

      // 计算压缩后的尺寸，保持宽高比
      let width = img.width
      let height = img.height
      const maxSize = 800 // 最大尺寸

      if (width > height && width > maxSize) {
        height = Math.round((height * maxSize) / width)
        width = maxSize
      } else if (height > maxSize) {
        width = Math.round((width * maxSize) / height)
        height = maxSize
      }

      // 设置canvas尺寸
      canvas.width = width
      canvas.height = height

      // 绘制图像
      ctx?.drawImage(img, 0, 0, width, height)

      // 获取压缩后的base64，降低质量到0.6
      const quality = 0.6 // 降低质量以减小文件大小
      const compressedBase64 = canvas.toDataURL(file.type, quality)

      // 移除 data:image/jpeg;base64, 前缀
      const base64Data = compressedBase64.split(',')[1]
      signForm.PhotoBase64 = base64Data
      imageUrl.value = compressedBase64
    }
  }
}

// 取消标志牌表单
const cancelSignForm = () => {
  signFormVisible.value = false
  resetSignForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }

  isDrawing.value = false
}

// 重置标志牌表单
const resetSignForm = () => {
  if (signFormRef.value) {
    signFormRef.value.resetFields()
  }

  signForm.SignType = ''
  signForm.Content = ''
  signForm.InstallationDate = ''
  signForm.BoardSize = ''
  signForm.Material = ''
  signForm.Status = '正常'
  signForm.LastInspectionDate = ''
  signForm.RoadSegmentID = ''
  signForm.PhotoBase64 = ''
  signForm.ExpectedLifespan = '10'
  signForm.MaintenanceDate = ''
  signForm.MaintenanceType = ''
  signForm.Description = ''
  signForm.DamagePercent = '0'

  imageUrl.value = ''
}

// 提交标志牌表单
const submitSignForm = async () => {
  if (!signFormRef.value) return

  await signFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新标志牌
        addSign()
      } else {
        // 更新标志牌
        updateSign()
      }
    }
  })
}

// 添加新标志牌
const addSign = () => {
  if (!tempGraphic || !signLayer) return

  // 创建新的标志牌图形
  const attributes = {
    SignType: signForm.SignType,
    Content: signForm.Content,
    InstallationDate: signForm.InstallationDate,
    BoardSize: signForm.BoardSize,
    Material: signForm.Material,
    Status: signForm.Status,
    LastInspectionDate: signForm.LastInspectionDate,
    RoadSegmentID: signForm.RoadSegmentID,
    PhotoBase64: signForm.PhotoBase64,
    ExpectedLifespan: signForm.ExpectedLifespan,
    Description: signForm.Description,
    DamagePercent: signForm.DamagePercent,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  signLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      console.log(result)
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('标志牌添加成功')
        signFormVisible.value = false
        resetSignForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.removeAll()
          tempGraphic = null
        }

        isDrawing.value = false
      } else {
        ElMessage.error('标志牌添加失败')
      }
    })
    .catch((error) => {
      console.error('添加标志牌出错:', error)
      ElMessage.error('标志牌添加失败')
    })
}

// 编辑标志牌
const editSign = () => {
  if (!selectedSign) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedSign.attributes
  signForm.SignType = attrs.SignType || ''
  signForm.Content = attrs.Content || ''
  signForm.InstallationDate = attrs.InstallationDate || ''
  signForm.BoardSize = attrs.BoardSize || ''
  signForm.Material = attrs.Material || ''
  signForm.Status = attrs.Status || '正常'
  signForm.LastInspectionDate = attrs.LastInspectionDate || ''
  signForm.RoadSegmentID = attrs.RoadSegmentID ? attrs.RoadSegmentID.toString() : ''
  signForm.PhotoBase64 = attrs.PhotoBase64 || ''
  signForm.ExpectedLifespan = attrs.ExpectedLifespan || '10'
  signForm.MaintenanceDate = attrs.MaintenanceDate || ''
  signForm.MaintenanceType = attrs.MaintenanceType || ''
  signForm.Description = attrs.Description || ''
  signForm.DamagePercent = attrs.DamagePercent || '0'

  // 如果有照片，显示照片
  if (attrs.PhotoBase64) {
    imageUrl.value = 'data:image/jpeg;base64,' + attrs.PhotoBase64
  } else {
    imageUrl.value = ''
  }

  signInfoVisible.value = false
  signFormVisible.value = true
}

// 更新标志牌
const updateSign = () => {
  if (!selectedSign || !signLayer) return

  // 更新属性
  const updatedGraphic = selectedSign.clone()
  updatedGraphic.attributes.SignType = signForm.SignType
  updatedGraphic.attributes.Content = signForm.Content
  updatedGraphic.attributes.InstallationDate = signForm.InstallationDate
  updatedGraphic.attributes.BoardSize = signForm.BoardSize
  updatedGraphic.attributes.Material = signForm.Material
  updatedGraphic.attributes.Status = signForm.Status
  updatedGraphic.attributes.LastInspectionDate = signForm.LastInspectionDate
  updatedGraphic.attributes.RoadSegmentID = signForm.RoadSegmentID
  updatedGraphic.attributes.PhotoBase64 = signForm.PhotoBase64
  updatedGraphic.attributes.ExpectedLifespan = signForm.ExpectedLifespan
  updatedGraphic.attributes.MaintenanceDate = signForm.MaintenanceDate
  updatedGraphic.attributes.MaintenanceType = signForm.MaintenanceType
  updatedGraphic.attributes.Description = signForm.Description
  updatedGraphic.attributes.DamagePercent = signForm.DamagePercent

  // 应用编辑
  signLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('标志牌更新成功')
        signFormVisible.value = false
        resetSignForm()
        // 强制刷新组件
        nextTick(() => {
          refreshSignKey.value++
        })
      } else {
        ElMessage.error('标志牌更新失败')
      }
    })
    .catch((error) => {
      console.error('更新标志牌出错:', error)
      ElMessage.error('标志牌更新失败')
    })
}

// 确认删除标志牌
const confirmDeleteSign = () => {
  signInfoVisible.value = false
  deleteConfirmVisible.value = true
}

// 删除标志牌
const deleteSign = () => {
  if (!selectedSign || !signLayer) return

  signLayer
    .applyEdits({
      deleteFeatures: [selectedSign],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('标志牌删除成功')
        deleteConfirmVisible.value = false
      } else {
        ElMessage.error('标志牌删除失败')
      }
    })
    .catch((error) => {
      console.error('删除标志牌出错:', error)
      ElMessage.error('标志牌删除失败')
    })
}

// 查询已上报错误的标志牌
const showReportedSigns = async () => {
  if (!signLayer) {
    ElMessage.warning('标志牌图层未加载')
    return
  }

  try {
    // 创建查询对象，查询状态为"待维修"或"损坏"的标志牌
    const query = new Query()
    query.where = "Status = '待维修' OR Status = '损坏'"
    query.outFields = ['*']
    query.returnGeometry = true

    // 执行查询
    const results = await signLayer.queryFeatures(query)

    if (results.features && results.features.length > 0) {
      // 保存原始的Graphic对象
      reportedSignsGraphics = results.features

      // 转换为普通JavaScript对象用于模板渲染
      reportedSigns.value = results.features.map((feature) => {
        return {
          signType: feature.attributes.SignType || '',
          content: feature.attributes.Content || '',
          status: feature.attributes.Status || '',
          description: feature.attributes.Description || '',
          installationDate: feature.attributes.InstallationDate || '',
          lastInspectionDate: feature.attributes.LastInspectionDate || '',
          roadSegmentID: feature.attributes.RoadSegmentID || '',
          // 添加其他需要的属性
        }
      })

      reportedSignsVisible.value = true
    } else {
      reportedSignsGraphics = []
      reportedSigns.value = []
      reportedSignsVisible.value = true
      ElMessage.info('未找到已上报错误的标志牌')
    }
  } catch (error) {
    console.error('查询已上报错误标志牌出错:', error)
    ElMessage.error('查询已上报错误标志牌失败')
  }
}

// 处理已上报标志牌行点击
const handleReportedSignClick = (row: any) => {
  // 获取对应的原始Graphic对象
  const graphicIndex = reportedSigns.value.indexOf(row)
  if (graphicIndex >= 0 && graphicIndex < reportedSignsGraphics.length) {
    const graphic = reportedSignsGraphics[graphicIndex]

    // 如果有地图视图，则定位到该标志牌
    if (view && graphic.geometry) {
      view.goTo({
        target: graphic.geometry,
        zoom: 15,
      })
    }
  }
}

// 查看已上报标志牌详情
const viewReportedSignDetail = (index: number) => {
  if (index >= 0 && index < reportedSignsGraphics.length) {
    selectedSign = reportedSignsGraphics[index]
    reportedSignsVisible.value = false
    signInfoVisible.value = true

    // 如果有地图视图，则定位到该标志牌
    if (view && selectedSign.geometry) {
      view.goTo({
        target: selectedSign.geometry,
        zoom: 15,
      })
    }
  }
}

// 根据道路ID获取道路名称
const getRoadNameById = (roadId: string | number) => {
  if (!roadId) return '未知道路'

  const road = roadList.find((road) => road.attributes.FID.toString() === roadId.toString())
  return road ? road.attributes.RoadName : '未知道路'
}

// 根据受损程度获取状态
const getDamageStatus = (damagePercent: string | number) => {
  const percent = Number(damagePercent || 0)
  if (percent >= 75) return 'exception' // 红色
  if (percent >= 50) return 'warning' // 黄色
  return 'success' // 绿色
}

// 加载道路列表
const loadRoadList = () => {
  if (!highwayLineLayer) return

  // 查询所有道路
  const query = highwayLineLayer.createQuery()
  query.outFields = ['FID', 'RoadName']
  query.returnGeometry = false

  highwayLineLayer
    .queryFeatures(query)
    .then((results) => {
      if (results.features && results.features.length > 0) {
        roadList = results.features
      }
    })
    .catch((error) => {
      console.error('加载道路列表出错:', error)
      ElMessage.error('加载道路列表失败')
    })
}

// 初始化地图
onMounted(() => {
  // 创建标志牌图层
  signLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/2',
    title: '标志牌',
    visible: Boolean(layerVisibility.value.sign),
    outFields: ['*'], // 确保所有字段都可用
    popupEnabled: false, // 禁用默认弹出窗口，使用自定义弹窗
  })

  // 创建草图图层
  sketchLayer = new GraphicsLayer({
    title: '绘图图层',
  })

  // 创建高速公路线图层
  highwayLineLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/3',
    title: '高速公路',
    visible: true,
    outFields: ['*'], // 确保所有字段都可用
    popupEnabled: false, // 禁用默认弹出窗口，使用自定义弹窗
  })

  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [signLayer, highwayLineLayer, sketchLayer], // 添加图层到地图
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 10,
    center: [116.7461293, 36.5598627], // 默认中心点（北京）
  })

  // 初始化绘图工具
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: sketchLayer,
    defaultCreateOptions: {
      mode: 'click', // 使用点击模式创建点
    },
  })

  // 监听绘图完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete') {
      isDrawing.value = false

      // 保存临时图形
      if (event.tool === 'point') {
        // 点绘制完成
        tempGraphic = new Graphic({
          geometry: event.graphic.geometry,
          symbol: new SimpleMarkerSymbol({
            color: [255, 0, 0, 0.8],
            size: 12,
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          }),
        })
        // 添加到草图图层
        sketchLayer?.add(tempGraphic)
        // 加载道路列表
        loadRoadList()
        // 显示标志牌表单
        formMode.value = 'add'
        signFormVisible.value = true
      }
    }
  })

  // 监听点击事件，用于查询标志牌和高速公路信息
  view.on('click', async function (event) {
    // 如果正在绘制，不执行查询
    if (isDrawing.value) return

    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 1 // 增加点击容差
    query.units = 'miles'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询标志牌图层
      if (signLayer && signLayer.visible) {
        // 强制刷新图层
        signLayer.refresh()
        const signResult = await signLayer.queryFeatures(query)
        if (signResult.features.length > 0) {
          // 找到标志牌，显示信息
          selectedSign = signResult.features[0]
          signInfoVisible.value = true
          nextTick(() => {
            refreshSignKey.value++
          })
          return
        }
      }

      // 查询高速公路图层
      if (highwayLineLayer && highwayLineLayer.visible) {
        // 强制刷新图层
        highwayLineLayer.refresh()
        const roadResult = await highwayLineLayer.queryFeatures(query)
        if (roadResult.features.length > 0) {
          // 找到高速公路，显示信息
          ElMessage.info(
            `点击了高速公路: ${roadResult.features[0].attributes.RoadName || '未命名道路'}`,
          )
          return
        }
      }
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })

  // 加载道路列表
  loadRoadList()
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (sketchViewModel) {
    sketchViewModel = null
  }

  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  width: 280px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .layer-control-panel {
    width: 220px;
    top: 10px;
    right: 10px;
  }
}
</style>
